package com.typhoon.spring_jdbctemplate.service.impl;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.typhoon.spring_jdbctemplate.compare.CompareContext;
import com.typhoon.spring_jdbctemplate.compare.CompareResult;
import com.typhoon.spring_jdbctemplate.compare.CompareRule;
import com.typhoon.spring_jdbctemplate.compare.IComparator;
import com.typhoon.spring_jdbctemplate.compare.UserComparetor;
import com.typhoon.spring_jdbctemplate.dao.UserDao;
import com.typhoon.spring_jdbctemplate.entity.User;
import com.typhoon.spring_jdbctemplate.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {


	static UserDao userDao = new UserDao();

	@Override
	//@Cacheable(value="testId",key="'id_'+#id")
	//@Cacheable(value="testId",keyGenerator = "customKeyGenerator")
	public User selectById(Long id) {
		User u = new User();
		SoftReference<User> studentSoftRef = new SoftReference<>(u);
		u = null;
		System.out.println(studentSoftRef.get());

		System.gc();
		System.out.println("After GC:");
		System.out.println(studentSoftRef.get());

		System.out.println("After a big object allocate:");
		byte[] b = new byte[1024 * 925 * 7];//分配一个大对象
		System.gc();

		System.out.println(studentSoftRef.get());//由于内存紧张，软引用会被清除
		return null;
	}

	@Override
	//@CacheEvict(value = "testId",key = "'id_'+#user.id")
	@CachePut(value="testId",key="'id_'+u.id")
	public User update(User user) {
		return userDao.update(user);
	}

	@Override
	public CompareResult<User> compareUserList(List<User> sourceList) {
		List<User> targetList = this.selectAll();
		CompareContext context = new CompareContext(sourceList, targetList);
		CompareRule rule = new CompareRule();
		String[] pk = new String[] { "id" };
		rule.setSourceAttrs(pk);
		rule.setTargetAttrs(pk);
		rule.setAutoUpdate(true);
		context.setRule(rule);
		IComparator<User, User> comparator = new UserComparetor();
		return comparator.compare(context);
	}

	@Override
	public List<User> selectAll() {
		return this.userDao.queryAll();
	}
}
